from flask import Flask, render_template, request, redirect, url_for, session
from flask_wtf import FlaskForm
from wtforms import IntegerField, StringField, TextField, TextAreaField, PasswordField, DateField, SubmitField
from SQLAlchemy import connect
import formclass
import time

app = Flask(__name__)
app.secret_key = 'SET_ME_BEFORE_USE_SESSION'
app.config["SECRET_KEY"] = '8aa47df44c5f4de6ae7b67b5c9a76bf1'


# 登录界面
@app.route('/', methods=['GET', 'POST'])
def log_in():
    form = formclass.LogInForm(request.form)
    print(session.new)
    # 判断用户密码是否为空
    if form.user.data and form.password.data:
        try:
            print('查询用户名')
            sign = connect.Get().LogIn(login_id=form.user.data)
            if sign.password == form.password.data:
                form.message.data = '密码正确'
                # 进行三种判断
                s = connect.Get().Admin(admin_id=form.user.data)
                if s is not None:
                    session['user_id'] = form.user.data
                    session['password'] = form.password.data
                    session['user'] = 'admin'
                    form.name = s.name
                    return redirect(url_for('admin'))
                s = connect.Get().Student(student_id=form.user.data)
                if s is not None:
                    session['user_id'] = form.user.data
                    session['password'] = form.password.data
                    session['user'] = 'student'
                    form.name = s.name
                    return redirect(url_for('student'))
                s = connect.Get().Teacher(teacher_id=form.user.data)
                if s is not None:
                    session['user_id'] = form.user.data
                    session['password'] = form.password.data
                    session['user'] = 'teacher'
                    form.name = s.name
                    return redirect(url_for('teacher'))
            else:
                form.message.data = '密码错误'
                return render_template('login.html', form=form)
        except:
            form.message.data = '用户名错误'
            return render_template('login.html', form=form)
    else:
        form.message.data = '用户名或密码为空'
    return render_template('login.html', form=form)


@app.route('/admin/', methods=['GET', 'POST'])
def admin():
    user = session.get('user')
    if user != 'admin':
        return redirect(url_for('log_in'))
    else:
        # 跳转按钮指定操作
        for i in request.form:
            return redirect(url_for(i))
        return render_template('admin.html')


# 学籍管理
@app.route('/admin_student_management', methods=['GET', 'POST'])
def admin_student_management():
    user = session.get('user')
    if user != 'admin':
        return redirect(url_for('log_in'))
    else:
        form = formclass.AdminStudentManagement()
        formlist = formclass.AdminStudentManagementList(request.form)
        if '提交' in request.form:
            for student in formlist.student_management_list:
                student_all=connect.Get().StudentMessageAll(student_id=student.student_id)
                if len(student_all)>1 or student.student_id==None:
                    continue
                #暂时不删除学生信息
                # if student.student_id.data==None:
                #     student_id=connect.Get().Student(name=student.student_name,telephone=student.student_telephone)
                #     connect.Delete.ChoiseCourse(student_id=student_id.student_id)
                #     connect.Delete.Mark(student_id=student_id.student_id)
                #     connect.Delete.Design(student_id=student_id.student_id)
                #     connect.Delete.Assess(student_id=student_id.student_id)
                #     connect.Delete.Student(student_id=student_id.student_id)

                else:
                    connect.Update.Student(student_id=student.student_id,name=student.student_name,gender=student.student_gender,telephone=student.student_telephone,class_id=student.student_class_id)


        students=connect.Get().StudentAll()
        for student in students:
            form.student_id=student.student_id
            form.student_name=student.name
            form.student_gender=student.gender
            form.student_telephone=student.telephone
            form.student_class_id=student.class_id
            formlist.student_management_list.append_entry(form)
        return render_template('admin_student_management.html',form=formlist)


# 老师管理
@app.route('/admin_teacher_manegement', methods=['GET', 'POST'])
def admin_teacher_manegement():
    user = session.get('user')
    if user != 'admin':
        return redirect(url_for('log_in'))
    else:
        form = formclass.AdminTeacherManagement()
        formlist = formclass.AdminTeacherManagementList(request.form)

        return render_template('admin_teacher_manegement.html', form=formlist)


# 成绩管理
@app.route('/admin_mark_management', methods=['GET', 'POST'])
def admin_mark_management():
    user = session.get('user')
    if user != 'admin':
        return redirect(url_for('log_in'))
    else:
        form = formclass.AdminMarkManagement()
        formlist = formclass.AdminMarkManagementList(request.form)

        return render_template('admin_mark_management.html', form=formlist)


# 选课管理
@app.route('/admin_choise_course_management', methods=['GET', 'POST'])
def admin_choise_course_management():
    user = session.get('user')
    if user != 'admin':
        return redirect(url_for('log_in'))
    else:
        form = formclass.AdminChoiseCourseManagement()
        formlist = formclass.AdminChoiseCourseManagementList(request.form)

        return render_template('admin_choise_course_management.html', form=formlist)


# 课表编排
@app.route('/admin_school_timetable_layout', methods=['GET', 'POST'])
def admin_school_timetable_layout():
    user = session.get('user')
    if user != 'admin':
        return redirect(url_for('log_in'))
    else:
        form = formclass.TeacherMarkManegement()
        formlist = formclass.TeacherMarkManegementList(request.form)

        return render_template('admin_school_timetable_layout.html', form=formlist)


# teacher
@app.route('/teacher', methods=['GET', 'POST'])
def teacher():
    user = session.get('user')
    if user != 'teacher':
        return redirect(url_for('log_in'))
    else:
        # 跳转按钮指定操作
        for i in request.form:
            return redirect(url_for(i))
        return render_template('teacher.html')


# 成绩查询及修改
@app.route('/teacher_mark_management', methods=['GET', 'POST'])
def teacher_mark_management():
    user = session.get('user')
    if user != 'teacher':
        return redirect(url_for('log_in'))
    else:
        form = formclass.TeacherMarkManegement()
        formlist = formclass.TeacherMarkManegementList(request.form)

        # 点击提交按钮，更改数据库
        if '提交' in request.form:
            for form in formlist.mark_list:
                if form.mark.data == None:
                    print('更改')
                    form.mark.data = 0
                mark = connect.Get().Mark(mark_id=form.mark_id.data)
                connect.Update().Mark(mark_id=form.mark_id.data, student_id=form.student_id.data,
                                      course_id=mark.course_id, mark=str(form.mark.data))
                # print(form.mark_id.data,form.mark.data)

        teacher = connect.Get().Teacher(teacher_id=int(session.get('user_id')))
        class_teachers = connect.Get().ClassTeacherAll(teacher_id=teacher.teacher_id)
        for class_teacher in class_teachers:
            students = connect.Get().StudentMessageAll(class_id=class_teacher.class_id)
            for student in students:
                mark = connect.Get().Mark(student_id=student.student_id)
                form.mark_id = mark.mark_id
                form.student_id = student.student_id
                form.student_name = student.name
                form.mark = mark.mark
                formlist.mark_list.append_entry(form)
        return render_template('teacher_mark_management.html', form=formlist)


# 教师课表
@app.route('/teacher_school_timetable', methods=['GET', 'POST'])
def teacher_school_timetable():
    user = session.get('user')
    if user != 'teacher':
        return redirect(url_for('log_in'))
    else:
        form = formclass.TeacherSchoolTimetable()
        formlist = formclass.TeacherSchoolTimetableList(request.form)
        teacher = connect.Get().Teacher(teacher_id=int(session.get('user_id')))
        school_time_tables = connect.Get().SchoolTimeTableAll(teacher_id=teacher.teacher_id)
        for school_time_table in school_time_tables:
            print(school_time_table.time_id)
            time_table = connect.Get().TimeTable(time_id=school_time_table.time_id)
            week = time_table.week
            time = time_table.time
            classroom = connect.Get().Classroom(classroom_id=school_time_table.classroom_id)
            classroom = classroom.name
            classs = connect.Get().Class(class_id=school_time_table.class_id)
            major = classs.major
            grade = classs.grade
            clas = classs.clas
            print(week, time, classroom, major, grade, clas)
            form.week = week
            form.time = time
            form.classroom = classroom
            form.major = major
            form.grade = grade
            form.clas = clas
            formlist.timetable_list.append_entry(form)
        return render_template('teacher_school_timetable.html', form=formlist)


@app.route('/teacher_design_management', methods=['GET', 'POST'])
def teacher_design_management():
    user = session.get('user')
    if user != 'teacher':
        return redirect(url_for('log_in'))
    else:
        form = formclass.TeacherDesignManagement()
        formlist = formclass.TeacherDesignManagementList(request.form)
        teacher = connect.Get().Teacher(teacher_id=session.get('user_id'))
        # 点击提交按钮，更改数据库
        if '提交' in request.form:
            for form in formlist.design_list:
                design = connect.Get().Design(design_id=form.design_id.data)
                if form.student_name.data == '':
                    connect.Update().Design(design_id=form.design_id.data, teacher_id=design.teacher_id,
                                            name=form.design_name.data)
                design = connect.Get().Design(design_id=form.design_id.data)
                connect.Update().Design(design_id=design.design_id, teacher_id=design.teacher_id,
                                        student_id=design.student_id, name=form.design_name.data)

        designs = connect.Get().DesignMessageAll(teacher_id=teacher.teacher_id)
        for design in designs:
            student = connect.Get().Student(student_id=design.student_id)
            # print(student)
            if student is not None:
                clas = connect.Get().Class(class_id=student.class_id)
                form.major = clas.major
                form.grade = clas.grade
                form.clas = clas.clas
                form.student_name = student.name
            else:
                form.major = ''
                form.grade = ''
                form.clas = ''
                form.student_name = ''

            form.design_id = design.design_id
            form.design_name = design.name
            formlist.design_list.append_entry(form)

        return render_template('teacher_design_management.html', form=formlist)


@app.route('/teacher_assess', methods=['GET', 'POST'])
def teacher_assess():
    user = session.get('user')
    if user != 'teacher':
        return redirect(url_for('log_in'))
    else:
        form = formclass.TeacherAssess()
        formlist = formclass.TeacherAssessList(request.form)
        teacher = connect.Get().Teacher(teacher_id=session.get("user_id"))
        assesss = connect.Get().AssessAll(teacher_id=teacher.teacher_id)
        for assess in assesss:
            form.student_name = connect.Get().Student(student_id=assess.student_id).name
            form.content = assess.content
            print(form.student_name)
            print(form.content)
            formlist.assess_list.append_entry(form)

        return render_template('teacher_assess.html', form=formlist)


@app.route('/student', methods=['GET', 'POST'])
def student():
    # 判断是否为学生，确定权限
    user = session.get('user')
    if user != 'student':
        return redirect(url_for('log_in'))
    else:
        # 跳转按钮指定操作
        for i in request.form:
            return redirect(url_for(i))
        return render_template('student.html')
        # return redirect(url_for('teacher'))


# admin五个功能模块
# class admin():
# @app.route('/school_roll_manage',methods=['GET','POST'])
# def school_roll_manage():
#     return render_template('school_roll_manage.html')
#
# @app.route('/teacher_manage',methods=['GET','POST'])
# def teacher_manage():
#     return render_template('teacher_manage.html')
# @app.route('/school_roll_manage',methods=['GET','POST'])
# def school_roll_manage():
#     return render_template('school_roll_manage.html')
#
# @app.route('/school_roll_manage',methods=['GET','POST'])
# def school_roll_manage():
#     return render_template('school_roll_manage.html')
#
# @app.route('/school_roll_manage',methods=['GET','POST'])
# def school_roll_manage():
#     return render_template('school_roll_manage.html')

# student五个模块
# 学生课表
@app.route('/student_school_timetable', methods=['GET', 'POST'])
def student_school_timetable():
    user = session.get('user')
    if user != 'student':
        return redirect(url_for('log_in'))
    else:
        # 定义表单
        form = formclass.StudentSchoolTimetable()
        formlist = formclass.StudentSchoolTimetableList(request.form)

        # 获取学生基本信息
        student = connect.Get().Student(student_id=int(session.get('user_id')))
        # 获取数据库中class_id班的课表信息
        student_school_timetable = connect.Get().SchoolTimeTable(class_id=student.class_id)
        print(student_school_timetable)
        # 为列表赋值
        for school_timetable in student_school_timetable:
            time_id = school_timetable.time_id
            time_table = connect.Get().TimeTable(time_id=time_id)
            week = time_table.week
            time = time_table.time
            classroom_id = school_timetable.classroom_id
            classroom = connect.Get().Classroom(classroom_id=classroom_id)
            place = classroom.name
            teacher_id = school_timetable.teacher_id
            teachers = connect.Get().Teacher(teacher_id=teacher_id)
            teacher = teachers.name
            course_id = teachers.course_id
            courses = connect.Get().Course(course_id=course_id)
            course = courses.course
            form.week = week
            form.time = time
            form.place = place
            form.teacher = teacher
            form.course = course
            formlist.timetable_list.append_entry(form)
        return render_template('student_school_timetable.html', form=formlist)


# 学生信息
@app.route('/student_message', methods=['GET', 'POST'])
def student_message():
    user = session.get('user')
    if user != 'student':
        return redirect(url_for('log_in'))
    else:
        form = formclass.StudentMessage(request.form)
        # 更改数据库信息信息
        if 'update' in request.form:
            student = connect.Get().Student(student_id=int(session.get('user_id')))
            connect.Update.Student(student_id=student.student_id, name=student.name, gender=student.gender,
                                   telephone=form.telephone.data, class_id=student.class_id)
        student = connect.Get().Student(student_id=int(session.get('user_id')))
        # 赋值
        form.student_id.data = student.student_id
        form.name.data = student.name
        form.gender.data = student.gender
        form.telephone.data = student.telephone
        form.class_id.data = student.class_id
        clas = connect.Get().Class(class_id=form.class_id.data)
        form.major.data = clas.major
        form.grade.data = clas.grade
        form.clas.data = clas.clas
        return render_template('student_message.html', form=form)


# 学生选课
@app.route('/student_choise_course', methods=['GET', 'POST'])
def student_choise_course():
    user = session.get('user')
    if user != 'student':
        return redirect(url_for('log_in'))
    else:
        form = formclass.StudentChoiseCourse()
        formlist = formclass.StudentChoiseCourseList()
        teachers = connect.Get().TeacherAll()
        c = [0, 0, 0, 0]
        for teacher_id in request.form:
            # 判断是否被选完
            choise_courses = connect.Get().ChoiseCourseAll()
            for i in choise_courses:
                c[i.teacher_id - 10017] = c[i.teacher_id - 10017] + 1
            if c[int(teacher_id) - 10017] <= 70:
                # 更改mark表
                teacher = connect.Get().ChoiseCourse(student_id=session.get('user_id'))
                teacher = connect.Get().Teacher(teacher_id=teacher.teacher_id)
                mark = connect.Get().Mark(student_id=session.get('user_id'), course_id=teacher.course_id)
                teacher = connect.Get().Teacher(teacher_id=teacher_id)
                connect.Update().Mark(mark_id=mark.mark_id, student_id=session.get('user_id'),
                                      course_id=teacher.course_id)

                # 更改assess表
                teacher = connect.Get().ChoiseCourse(student_id=session.get('user_id'))
                assess = connect.Get().Assess(teacher_id=teacher.teacher_id, student_id=session.get('user_id'))
                connect.Update().Assess(assess_id=assess.assess_id, teacher_id=teacher_id,
                                        student_id=session.get('user_id'), content=' ')

                # 更改choisecourse表
                connect.Delete().ChoiseCourse(student_id=session.get('user_id'))
                connect.Insert().ChoiseCourse(teacher_id=int(teacher_id), student_id=session.get('user_id'))
                j = connect.Get().ChoiseCourse(student_id=session.get('user_id'))
        # 对前端需要数据赋值
        c = [0, 0, 0, 0]
        choise_courses = connect.Get().ChoiseCourseAll()
        for i in choise_courses:
            c[i.teacher_id - 10017] = c[i.teacher_id - 10017] + 1
        for teacher in teachers:
            if teacher.teacher_id > 10016:
                course = connect.Get().Course(course_id=teacher.course_id)
                form.teacher_id = teacher.teacher_id
                form.teacher_name = teacher.name
                form.course = course.course
                form.count = 70 - c[teacher.teacher_id - 10017]
                formlist.student_choise_course_list.append_entry(form)
        course = connect.Get().ChoiseCourse(student_id=session.get('user_id'))
        teacher = connect.Get().Teacher(teacher_id=course.teacher_id)
        formlist.teacher_name = teacher.name
        return render_template('student_choise_course.html', form=formlist)


# 教师评价
@app.route('/student_assess_teacher', methods=['GET', 'POST'])
def student_assess_teacher():
    user = session.get('user')
    if user != 'student':
        return redirect(url_for('log_in'))
    else:
        form = formclass.StudentAssessTeacher()
        formlist = formclass.StudentAssessTeacherList()
        assesses = connect.Get().AssessAll(student_id=session.get('user_id'))
        # 点击提交按钮，更改数据库
        if '提交' in request.form:
            for assess, form in zip(assesses, formlist.assess_list):
                teacher = connect.Get().Teacher(teacher_id=assess.teacher_id)
                connect.Update().Assess(assess_id=assess.assess_id, teacher_id=assess.teacher_id,
                                        student_id=assess.student_id, content=form.assess.data)
                form.teacher = teacher.name
                content = connect.Get().Assess(assess_id=assess.assess_id)
                form.assess = content.content
                print(teacher.name, form.assess)
            lens = len(formlist.assess_list)
            for i in range(lens):
                formlist.assess_list.pop_entry()
        # 前端数据赋值
        assesses = connect.Get().AssessAll(student_id=session.get('user_id'))
        for assess in assesses:
            teacher = connect.Get().Teacher(teacher_id=assess.teacher_id)
            form.teacher = teacher.name
            form.assess = assess.content
            # print(form.teacher,form.assess)
            formlist.assess_list.append_entry(form)
        return render_template('student_assess_teacher.html', form=formlist)


# 毕业设计选择
@app.route('/student_choise_design', methods=['GET', 'POST'])
def student_choise_design():
    user = session.get('user')
    if user != 'student':
        return redirect(url_for('log_in'))
    else:
        form = formclass.StudentChoiseDesign()
        formlist = formclass.StudentChoiseDesignList()
        # 查询点击的是哪个按钮，并更改数据库
        for id in request.form:
            design = connect.Get().Design(student_id=session.get('user_id'))
            if not design:
                # connect.Update().Design(design_id=design.design_id,teacher_id=design.teacher_id,name=design.name)

                design = connect.Get().Design(design_id=id)
                connect.Update().Design(design_id=id, teacher_id=design.teacher_id, student_id=session.get('user_id'),
                                        name=design.name)
        # 为前端信息赋值
        designs = connect.Get().DesignAll()
        for design in designs:
            teacher = connect.Get().Teacher(teacher_id=design.teacher_id)
            form.design_id = design.design_id
            form.teacher = teacher.name
            form.design = design.name
            form.student_id = design.student_id
            formlist.design_list.append_entry(form)
        # 查询已经选择的毕设
        design = connect.Get().Design(student_id=session.get('user_id'))
        print(design)
        if design != None:
            print('design.student_id', design.student_id)
            print(design.design_id)
            form.design_id = design.design_id
            teacher = connect.Get().Teacher(design.teacher_id)
            form.teacher = teacher.name
            form.design = design.name
            form.student_id = design.student_id
            formlist.choise_design = form
        else:
            form.design_id = ''
            form.teacher = ''
            form.design = ''
            form.student_id = ''
            formlist.choise_design = form

        return render_template('student_choise_design.html', form=formlist)


if __name__ == '__main__':
    app.run()
